// pages/activity_detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0, // 导航栏总高度 = 状态栏高度 + 导航栏高度
    contentTop: 0, // 内容区域top位置
    activityId: 0, // 当前活动ID
    activityData: null, // 活动详情数据
    isCollected: false, // 是否已收藏
    showShareModal: false, // 是否显示分享弹窗
    currentImageIndex: 0, // 当前轮播图索引
    bottomSafeArea: 0, // 底部安全区域高度
    showRegistrationModal: false, // 是否显示报名弹窗
    isLoggedIn: false, // 登录状态
    userInfo: null // 用户信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取活动ID
    const activityId = options.id || 1
    console.log('活动详情页加载，活动ID:', activityId)
    
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44 // 44是导航栏内容高度
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      activityId: activityId,
      bottomSafeArea
    })
    
    // 根据活动ID加载详情数据
    this.loadActivityDetail(activityId)
    
    // 检查登录状态
    this.checkLoginStatus()
    
    // 检查收藏状态（从本地缓存读取）
    this.checkCollectionStatus()
    
    // 启用分享菜单
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  
  /**
   * 加载活动详情数据
   */
  async loadActivityDetail(activityId) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })

      console.log('开始获取活动详情，ID:', activityId)

      const result = await wx.cloud.callFunction({
        name: 'getActivityDetail',
        data: {
          activityId: activityId
        }
      })

      console.log('活动详情获取结果：', result)

      if (result.result && result.result.success) {
        const activityData = result.result.data
        
        // 处理活动数据，确保字段映射正确
        const processedData = {
          id: activityData._id || activityData.id,
          title: activityData.eventTitle || activityData.title,
          subtitle: activityData.subtitle || activityData.eventName,
          bannerImages: activityData.bannerImages || [activityData.bannerImage],
          detailImages: activityData.detailImages || activityData.bannerImages || [activityData.bannerImage],
          status: activityData.status,
          statusColor: activityData.statusColor,
          startTime: activityData.startTime,
          endTime: activityData.endTime,
          location: activityData.location,
          address: activityData.address,
          latitude: activityData.latitude,
          longitude: activityData.longitude,
          organizer: activityData.organizer,
          type: activityData.type, // 添加活动类型字段
          maxParticipants: activityData.maxParticipants,
          currentParticipants: activityData.signedUpCount || activityData.currentParticipants,
          price: activityData.price,
          tags: activityData.tags,
          description: activityData.description,
          highlights: activityData.highlights,
          schedule: activityData.schedule,
          requirements: activityData.requirements,
          contact: activityData.contact
        }

        this.setData({
          activityData: processedData,
          markers: [{
            id: 0,
            latitude: processedData.latitude,
            longitude: processedData.longitude,
            title: processedData.location,
            address: processedData.address,
            iconPath: '/images/icons/location.png',
            width: 30,
            height: 30
          }]
        })

        console.log('活动详情加载成功:', processedData.title)
      } else {
        console.error('活动详情获取失败：', result.result?.message || '未知错误')
        wx.showToast({
          title: result.result?.message || '活动不存在',
          icon: 'none',
          duration: 2000
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }
    } catch (error) {
      console.error('加载活动详情出错：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
    } finally {
      wx.hideLoading()
    }
  },

  /**
   * 轮播图切换事件
   */
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current
    })
  },

  /**
   * 收藏/取消收藏
   */
  async toggleCollect() {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: '需要登录',
        content: '请先登录后再进行收藏操作',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/index'
            })
          }
        }
      })
      return
    }

    try {
      wx.showLoading({
        title: '处理中...',
        mask: true
      })

      const action = this.data.isCollected ? 'remove' : 'add'
      const result = await wx.cloud.callFunction({
        name: 'toggleCollection',
        data: {
          itemId: this.data.activityId,
          itemType: 'activity',
          action: action
        }
      })

      if (result.result && result.result.success) {
        const isCollected = result.result.isCollected
        this.setData({
          isCollected
        })
        
        // 缓存收藏状态到本地
        this.cacheCollectionStatus(isCollected)
        
        wx.showToast({
          title: result.result.message,
          icon: 'success',
          duration: 1500
        })
      } else {
        wx.showToast({
          title: result.result?.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('收藏操作失败：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    
    this.setData({
      isLoggedIn: isLoggedIn,
      userInfo: userInfo
    })
  },

  /**
   * 报名活动
   */
  registerActivity() {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: '需要登录',
        content: '请先登录后再进行报名',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/index'
            })
          }
        }
      })
      return
    }

    // 显示报名弹窗（按钮始终可用，后端会检查是否已报名）
    this.setData({
      showRegistrationModal: true
    })
  },

  /**
   * 关闭报名弹窗
   */
  onCloseRegistrationModal() {
    this.setData({
      showRegistrationModal: false
    })
  },

  /**
   * 报名成功回调
   */
  onRegistrationSuccess(e) {
    const { registrationId, totalAmount, cashbackAmount, newBalance } = e.detail
    
    // 关闭报名弹窗
    this.setData({
      showRegistrationModal: false
    })
    
    // 更新参与人数
    const activityData = this.data.activityData
    if (activityData) {
      activityData.currentParticipants = (activityData.currentParticipants || 0) + 1
      this.setData({
        activityData
      })
    }
    
    // 页面弹窗已移除，由组件内弹窗处理成功提示
  },


  /**
   * 联系主办方
   */
  contactOrganizer() {
    const contact = this.data.activityData.contact
    wx.showActionSheet({
      itemList: [`拨打电话：${contact.phone}`, `微信联系：${contact.wechat}`, `邮箱联系：${contact.email}`],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            wx.makePhoneCall({
              phoneNumber: contact.phone
            })
            break
          case 1:
            wx.setClipboardData({
              data: contact.wechat,
              success: () => {
                wx.showToast({
                  title: '微信号已复制',
                  icon: 'success'
                })
              }
            })
            break
          case 2:
            wx.setClipboardData({
              data: contact.email,
              success: () => {
                wx.showToast({
                  title: '邮箱已复制',
                  icon: 'success'
                })
              }
            })
            break
        }
      }
    })
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const current = e.currentTarget.dataset.src
    const urls = this.data.activityData.bannerImages
    
    wx.previewImage({
      current,
      urls
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次页面显示时检查登录状态
    this.checkLoginStatus()
    
    // 检查收藏状态（从本地缓存读取）
    this.checkCollectionStatus()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享或分享按钮
   */
  onShareAppMessage() {
    if (!this.data.activityData) {
      return {
        title: '活动详情',
        path: `/pages/activity_detail/index?id=${this.data.activityId}`
      }
    }
    
    return {
      title: this.data.activityData.title,
      path: `/pages/activity_detail/index?id=${this.data.activityData.id}`,
      imageUrl: this.data.activityData.bannerImages[0] || '/images/default-activity.png'
    }
  },

  /**
   * 检查收藏状态（优先从本地缓存读取）
   */
  checkCollectionStatus() {
    // 如果用户未登录，跳过状态检查
    if (!this.data.isLoggedIn || !this.data.userInfo) {
      return
    }

    try {
      const userOpenid = this.data.userInfo._openid
      const cacheKey = `activity_collect_${userOpenid}_${this.data.activityId}`
      
      // 优先从本地缓存读取收藏状态
      const cachedStatus = wx.getStorageSync(cacheKey)
      if (cachedStatus !== undefined && cachedStatus !== null) {
        this.setData({
          isCollected: cachedStatus
        })
        console.log('从本地缓存读取收藏状态:', cachedStatus)
        return
      }

      // 如果本地没有缓存，再从云端获取
      this.fetchCollectionStatusFromCloud()
    } catch (error) {
      console.error('读取收藏状态缓存失败：', error)
      // 如果读取缓存失败，从云端获取
      this.fetchCollectionStatusFromCloud()
    }
  },

  /**
   * 从云端获取收藏状态
   */
  async fetchCollectionStatusFromCloud() {
    if (!this.data.isLoggedIn) {
      return
    }

    try {
      const result = await wx.cloud.callFunction({
        name: 'getCollectionStatus',
        data: {
          itemId: this.data.activityId,
          itemType: 'activity'
        }
      })

      if (result.result && result.result.success) {
        const isCollected = result.result.isCollected || false
        this.setData({
          isCollected: isCollected
        })
        
        // 缓存到本地
        this.cacheCollectionStatus(isCollected)
        console.log('从云端获取收藏状态:', isCollected)
      }
    } catch (error) {
      console.error('获取收藏状态失败：', error)
    }
  },

  /**
   * 缓存收藏状态到本地
   */
  cacheCollectionStatus(isCollected) {
    if (!this.data.userInfo) {
      return
    }

    try {
      const userOpenid = this.data.userInfo._openid
      const cacheKey = `activity_collect_${userOpenid}_${this.data.activityId}`
      wx.setStorageSync(cacheKey, isCollected)
    } catch (error) {
      console.error('缓存收藏状态失败：', error)
    }
  },

  /**
   * 打开地图导航
   */
  openMap() {
    const { activityData } = this.data
    if (!activityData.latitude || !activityData.longitude) {
      wx.showToast({
        title: '位置信息不完整',
        icon: 'none'
      })
      return
    }

    wx.openLocation({
      latitude: activityData.latitude,
      longitude: activityData.longitude,
      name: activityData.location,
      address: activityData.address,
      scale: 16
    })
  },

  /**
   * 返回按钮点击事件
   */
  handleBack() {
    wx.navigateBack()
  }
})